package com.piece.mall.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.bootstrap.TreeData;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.mall.model.WmsShArea;
import com.piece.mall.service.WmsShAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = {"全国地区省份管理"})
@RequestMapping("/api/mall/ware/area")
public class WmsShAreaController extends FrameWorkController {

    @Resource
    private WmsShAreaService wmsShAreaService;

    @PostMapping("/list")
    @ApiOperation(value = "查询全国省市区列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = wmsShAreaService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @ApiOperation(value = "查询全国省市区分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = wmsShAreaService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @ApiOperation(value = "加载全国省市区表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        Long pid = Convert.toLong(getRequest().getParameter("pid"), null);
        WmsShArea area = new WmsShArea();
        if (null != pid) {
            WmsShArea pArea = wmsShAreaService.findById(pid);
            area.setPid(pid);
            if (null != pArea) {
                area.setLevel(pArea.getLevel() + 1);
            } else {
                area.setLevel(1L);
            }
        } else if (id != 0) {
            area = wmsShAreaService.findById(pid);
        }

        return success(area);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "mall:mall")
    @ApiOperation(value = "保存全国省市区表单数据")
    @ApiImplicitParam(value = "全国省市区数据", dataTypeClass = WmsShArea.class, type = "body")
    public AjaxResponse save() {
        WmsShArea area;
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            if (null != id) {
                area = wmsShAreaService.findById(id);
            } else {
                area = new WmsShArea();
            }
            initDB(area);
            wmsShAreaService.insertOrUpdate(area);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "mall:mall")
    @ApiOperation(value = "删除全国省市区数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        wmsShAreaService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "mall:mall")
    @ApiOperation(value = "删除全国省市区数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            wmsShAreaService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @PostMapping("/treeData")
    @ApiOperation(value = "加载全国省市区列表树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "请求来源"),
            @ApiImplicitParam(name = "selected", value = "已选ID集合"),
            @ApiImplicitParam(name = "parentId", value = "上级分类ID"),
            @ApiImplicitParam(name = "excludeRoot", value = "是否排除Root节点")
    })
    public List<TreeData> treeData() {
        String selected = getRequest().getParameter("selected");
        Long parentId = Convert.toLong(getRequest().getParameter("parentId"));
        String excludeRoot = getRequest().getParameter("excludeRoot");
        // 请求来源
        String from = getRequest().getParameter("from");
        List<TreeData> result;
        List<WmsShArea> list;
        if (null != parentId) {
            list = wmsShAreaService.findByParent(parentId);
        } else {
            list = wmsShAreaService.findAll();
        }
        if (StringUtil.isNotEmpty(selected)) {
            result = wmsShAreaService.findTreeData(list, Convert.toStrList(selected));
            return result;
        } else {
            result = wmsShAreaService.findTreeData(list);
        }

        if ("vue".equals(from)) {
            TreeData root = TreeData.builder().id("0").name("中国").build();
            result = findChildTreeData(result, Convert.toStr(parentId, root.getId()));
            if ("true".equals(excludeRoot)) {
                return result;
            }
            root.setChildren(result);
            List<TreeData> convertResult = new ArrayList<>();
            convertResult.add(root);
            return convertResult;
        }
        return result;
    }
}
